package com.jlstu.daijia.customer.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jlstu.daijia.common.execption.GuiguException;
import com.jlstu.daijia.common.result.ResultCodeEnum;
import com.jlstu.daijia.customer.mapper.CustomerInfoMapper;
import com.jlstu.daijia.customer.mapper.CustomerLoginLogMapper;
import com.jlstu.daijia.customer.service.CustomerInfoService;
import com.jlstu.daijia.model.entity.customer.CustomerInfo;
import com.jlstu.daijia.model.entity.customer.CustomerLoginLog;
import com.jlstu.daijia.model.form.customer.UpdateWxPhoneForm;
import com.jlstu.daijia.model.vo.customer.CustomerLoginVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 客户信息管理服务实现类。
 * 该类继承自ServiceImpl，实现了CustomerInfoService接口，
 * 提供了客户信息的登录和管理功能。
 */
@RequiredArgsConstructor
@Slf4j
@Service
@SuppressWarnings({"unchecked", "rawtypes"})
public class CustomerInfoServiceImpl extends ServiceImpl<CustomerInfoMapper, CustomerInfo> implements CustomerInfoService {

    private final WxMaService wxMaService;
    private final CustomerLoginLogMapper customerLoginLogMapper;
    private final CustomerInfoMapper customerInfoMapper;

    /**
     * 小程序用户登录接口。
     * 通过微信小程序的code换取openid，进而实现用户登录。
     * 如果用户已存在，直接返回用户ID；如果用户不存在，则创建新用户并返回其ID。
     *
     * @param code 小程序登录时获取的code。
     * @return 用户ID。
     */
    @Override
    public Long login(String code) {
        String openid;
        try {
            // 使用微信小程序服务获取用户session信息，包括openid。
            WxMaJscode2SessionResult sessionInfo = wxMaService.getUserService().getSessionInfo(code);
            openid = sessionInfo.getOpenid();
        } catch (WxErrorException e) {
            // 如果获取session信息失败，抛出运行时异常。
            throw new RuntimeException(e);
        }

        // 根据openid查询用户信息，如果用户不存在则创建新用户。
        CustomerInfo customerInfo = this.getOne(new LambdaQueryWrapper<CustomerInfo>().eq(CustomerInfo::getWxOpenId, openid));
        if (customerInfo == null) {
            // 为新用户设置默认昵称和头像，并保存到数据库。
            // 新增客户信息
            customerInfo = new CustomerInfo();
            customerInfo.setNickname(String.valueOf(System.currentTimeMillis()));
            customerInfo.setAvatarUrl("https://oss.aliyuncs.com/aliyun_id_photo_bucket/default_handsome.jpg");
            customerInfo.setWxOpenId(openid);
            this.save(customerInfo);
        }

        // 记录用户登录日志。
        CustomerLoginLog customerLoginLog = new CustomerLoginLog();
        customerLoginLog.setCustomerId(customerInfo.getId());
        customerLoginLog.setMsg("小程序登录");
        customerLoginLogMapper.insert(customerLoginLog);

        // 返回用户ID。
        return customerInfo.getId();
    }

    @Override
    public CustomerLoginVo getCustomerInfo(Long customerId) {
        CustomerInfo customerInfo = this.getById(customerId);
        CustomerLoginVo customerLoginVo = new CustomerLoginVo();
        BeanUtils.copyProperties(customerInfo, customerLoginVo);
        String phone = customerInfo.getPhone();
        boolean isBindPhone = StringUtils.hasText(phone);
        customerLoginVo.setIsBindPhone(isBindPhone);
        return customerLoginVo;
    }

    @Override
    public Boolean updateWxPhoneNumber(UpdateWxPhoneForm updateWxPhoneForm) {
        //1 根据code值获取微信绑定手机号码
        try {
            WxMaPhoneNumberInfo phoneNoInfo = wxMaService.getUserService().getPhoneNoInfo(updateWxPhoneForm.getCode());
            String phoneNumber = phoneNoInfo.getPhoneNumber();

            //更新用户信息
            Long customerId = updateWxPhoneForm.getCustomerId();
            CustomerInfo customerInfo = this.getById(customerId);
            customerInfo.setPhone(phoneNumber);
            this.updateById(customerInfo);

            return true;
        } catch (WxErrorException e) {
            throw new GuiguException(ResultCodeEnum.DATA_ERROR);
        }
    }

    @Override
    public String getCustomerOpenId(Long customerId) {
        LambdaQueryWrapper<CustomerInfo> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(CustomerInfo::getId,customerId);
        CustomerInfo customerInfo = customerInfoMapper.selectOne(wrapper);
        return customerInfo.getWxOpenId();
    }
}
